package com.fc2.blog96.nonbirimuchiki.SlideShowClient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;



public class ImageNetworkThread implements Runnable//extends AsyncTask<Void, Void, Bitmap>
{
	private ImageView mImage;
	private Context mContext;
	//private BluetoothManager mBtManager;
	private InputStream mInput;
	private OutputStream mOutput;
	private BufferedWriter mWriter;
	private BufferedReader mReader;
	private ImageInfo mImageInfo;
	private Bitmap mBitmap;
	private boolean isActive = false;
	private Lock mLock =new ReentrantLock();
	private SlideShowClientActivity mActivity;
	private boolean readyflg = false;

	//コンストラクタ
	ImageNetworkThread(Context context)
	{
		mContext = context;
		mActivity = (SlideShowClientActivity)context;
		mImageInfo = new ImageInfo();

		//mBtManager = bt;
		try {
			BluetoothManager.btClientSocket = BluetoothManager.btDevice.createRfcommSocketToServiceRecord(common.MUCHIKI0226_UUID);
			BluetoothManager.btAdapter.cancelDiscovery();
			BluetoothManager.btClientSocket.connect();
			mInput = BluetoothManager.btClientSocket.getInputStream();
			mOutput = BluetoothManager.btClientSocket.getOutputStream();
			mWriter = new BufferedWriter(new OutputStreamWriter(BluetoothManager.btClientSocket.getOutputStream()));
			mReader = new BufferedReader(new InputStreamReader(BluetoothManager.btClientSocket.getInputStream()));
			readyflg =true;
		} catch (IOException e) {
			try {
				if(mInput!=null)mInput.close();
				if(mOutput!=null)mOutput.close();
				if(mWriter!=null)mWriter.close();
				if(mReader!=null)mReader.close();
				BluetoothManager.btClientSocket.close();
				BluetoothManager.btClientSocket = null;
				mActivity.showErrorDialog("接続できません", "別の接続先を指定してください。", "OK", common.AlertDialogMode.ALERT_DIALOG_MODE_FINISH);
			} catch (IOException e1) {
				// TODO 自動生成された catch ブロック
				e1.printStackTrace();
			}
		}
	}

	public void cancel()
	{
		if(BluetoothManager.btClientSocket != null)
		{
			try {
				mInput.close();
				mOutput.close();
				mWriter.close();
				mReader.close();
				BluetoothManager.btClientSocket.close();
			} catch (IOException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
		}
	}

    //メッセージを取得する
    private String getMessage()
    {
    	return readLine();
    }

    //イメージを取得する
    private void getImage()
    {

    	//イメージ情報取得リクエスト
    	sendMessage(common.SocketRequest.IMAGE_INFO_REQUEST);
    	String imageinfo = getMessage();
    	Log.e("tets",imageinfo);

    	int s = imageinfo.indexOf(common.SocketRequest.ImageInfo.WIDTH_START);
    	int e = imageinfo.indexOf(common.SocketRequest.ImageInfo.WIDTH_END);
    	mImageInfo.width =  Integer.parseInt(imageinfo.substring(s+common.SocketRequest.ImageInfo.WIDTH_START.length(), e));
    	s = imageinfo.indexOf(common.SocketRequest.ImageInfo.HEIGHT_START);
    	e = imageinfo.indexOf(common.SocketRequest.ImageInfo.HEIGHT_END);
    	mImageInfo.height =  Integer.parseInt(imageinfo.substring(s+common.SocketRequest.ImageInfo.HEIGHT_START.length(), e));
    	s = imageinfo.indexOf(common.SocketRequest.ImageInfo.PIXEL_START);
    	e = imageinfo.indexOf(common.SocketRequest.ImageInfo.PIXEL_END);
    	mImageInfo.pix =  Integer.parseInt(imageinfo.substring(s+common.SocketRequest.ImageInfo.PIXEL_START.length(), e));
    	s = imageinfo.indexOf(common.SocketRequest.ImageInfo.DATASIZE_START);
    	e = imageinfo.indexOf(common.SocketRequest.ImageInfo.DATASIZE_END);
    	mImageInfo.size =  Integer.parseInt(imageinfo.substring(s+common.SocketRequest.ImageInfo.DATASIZE_START.length(), e));
     	byte pixels[] = new byte[mImageInfo.size];

    	//イメージデータ取得リクエスト
    	sendMessage2(common.SocketRequest.IMAGE_DATA_REQUEST);
    	read(pixels,pixels.length);

		mLock.lock();
		try {
			mBitmap = BitmapFactory.decodeByteArray(pixels,0,pixels.length);
		} finally {
			mLock.unlock();
		}

    }

    //メッセージを送信する
    private void sendMessage(String message)
    {
    	String str = "";
    	String recieve = "OK SEND IMAGE";
    	write(message);
    	str = readLine();
    	Log.e("test",str);
    }

    //メッセージを送信する
    private void sendMessage2(String message)
    {
    	write(message);
    }


    //バイナリ読み込み
    private int read(byte[] buf,int offset, int size)
    {
    	int s = 0;
    	try {
			s = mInput.read(buf, offset, size);
		} catch (IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
    	return s;
    }

    //バイナリ書き込み
    private void write(byte[] buf,int offset, int size)
    {
    	try {
			mOutput.write(buf, offset, size);
		} catch (IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
    }

    //文字列読み込み
    private String readLine()
    {
    	String str=null;
    	try {
			str = mReader.readLine();
		} catch (IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
    	return str;
    }

    //文字列書き込み
    private void write(String str)
    {
    	try {
			mWriter.write(str);
			mWriter.flush();
		} catch (IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
    }

    private int read(byte[] data,int size)
    {
    	int bufpos = 0;
    	while(true)
    	{
    		if(bufpos >= size)
    		{
    			break;
    		}
    		else
    		{
    			int ret;
				try {
					ret = mInput.read(data, bufpos, size - bufpos);
					bufpos+=ret;

				} catch (IOException e) {
					// TODO 自動生成された catch ブロック
					e.printStackTrace();
				}

    		}
    	}


    	return size;
    }

    public void cancelBluetooth()
    {
    	isActive = false;
    }

	@Override
	public void run() {
		if(readyflg)
		{
			isActive = true;
			int count = 0;
			while(isActive)
			{
				getImage();
			}
			try {
				mInput.close();
				mOutput.close();
				mWriter.close();
				mReader.close();
				BluetoothManager.btClientSocket.close();
				BluetoothManager.btClientSocket = null;
			} catch (IOException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
		}

	}

	public Bitmap getImageViewBitmap()
	{
		Bitmap ret = null;
		mLock.lock();
		try {
			ret = mBitmap;
		} finally {
			mLock.unlock();
		}
		return ret;
	}
}

